<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/06/10
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpAllocation;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 调拨管理
 * @package app\erp\model
 */
class GoodsWarehouseStockNumlogic{

    /**
     * 分店商品库存展示
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function index($user_id, $type, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'user_id' => $user_id,
                'sid' => $store_id,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/

            $list_mag =  model('ErpGoodsWarehouseStockNum', 'model') -> index($store_id,$type);//获取列表
            $list = $list_mag['data'];
            $rel_list = [];
            $sku_status = ['默认','可销售','不可销售'];
            foreach($list as $key => $value){
                $rel_list[$key]['id'] 			               = (int)$value['id'];
                $rel_list[$key]['title']                       = (string)$value['title'];
                $rel_list[$key]['address']                     = (string)$value['address'];
                $rel_list[$key]['wcode']                       = (string)$value['wcode'];
                $rel_list[$key]['goodsId']                     = (int)$value['goods_id'];
                $rel_list[$key]['goodsName']                   = (string)$value['goods_name'];
                $rel_list[$key]['skuId']                       = (int)$value['sku_id'];
                $rel_list[$key]['stockNum']                    = (int)$value['stock_num'];
                $rel_list[$key]['frozenNum']                   = (int)$value['frozen_num'];
                $rel_list[$key]['availableNum']                = (int)$value['available_num'];
                $rel_list[$key]['specifications1AttributeId']  = (int)$value['specifications1_attribute_id'];
                $rel_list[$key]['specifications2AttributeId']  = (int)$value['specifications2_attribute_id'];
                $rel_list[$key]['coverUrl']                    = (string)$value['cover_url'];
                $rel_list[$key]['code']                        = (string)$value['code'];
                $rel_list[$key]['price']                       = (string)$value['price'];
                $rel_list[$key]['inventory']                   = (int)$value['inventory'];
                $rel_list[$key]['createTime']                  = (string)$value['create_time'];
                $rel_list[$key]['updateTime']                  = (string)$value['update_time'];
                $rel_list[$key]['skuStatus']                   = (string)$sku_status[$value['sku_status']?:'0'];
                $rel_list[$key]['goodsSpecifications']         = (string)$value['goods_specifications'];
            }

            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/

        } catch (\Exception $e) {
            DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 根据门店id 和 skuid 查询库存
     * @param  int    $user_id   操作用户ID
     * @author jason
     * @return mixed
     */
    public function getKucunNum($store_id, $sku_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'store_id' 	                                => $store_id,
                'sku_id' 	                                => $sku_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            if($store_id > 0){
                //根据门店id 查询出仓库的id
                $warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
                foreach ($warehouse_list['data'] as $key => $value) {
                    if($value['type'] == 1){//分店仓库
                        $store_warehouse_list[] = $value['wid'];
                    }
                }
                //根据仓库id 查询库存数
                if($store_warehouse_list){
                    $map = [];
                    $map[] = ['sku_id', '=', $sku_id];
                    $map[] = ['warehouse_id', '=', $store_warehouse_list[0]];
                    
                    //$map['sku_id'] = $sku_id;
                    ////$map['warehouse_id'] = ['in', $store_warehouse_list];
                    $list = model('ErpGoodsWarehouseStockNum')-> field('stock_num, frozen_num, available_num, price, sku_status') -> where($map)  -> find();
                    // dump($list);
                    if($list) $list = $list->toArray();
                }
            }else{
                $map = [];
                $map[] = ['sku_id', '=', $sku_id];
                //$map[] = ['warehouse_id', '=', $store_warehouse_list[0]];
                
                //$map['sku_id'] = $sku_id;
                ////$map['warehouse_id'] = ['in', $store_warehouse_list];
                $list = model('ErpGoodsWarehouseStockNum')-> field('sum(stock_num) as stock_num, sum(frozen_num) as frozen_num, sum(available_num) as available_num, price, sku_status') -> group('price') -> where($map)  -> find();
                
                if($list) $list = $list->toArray();
            }
            if(!$list){
				DB::commit();
				return array_out(-1001, '该商店无货');
			} 
            $list['warehouse_id'] = $store_warehouse_list[0];
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

}